package simple.form.db;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.fastjson.JSONObject;
import com.xiaoleilu.hutool.db.DbRuntimeException;
import simple.form.utils.SafeConvertUtil;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * Created by Administrator on 2017/2/27.
 */
public class DefaultDataSource extends AbsDataSource {

    private DruidDataSource druidDataSource;


    /*配置初始化大小、最小、最大*/
    private int initialSize;
    private int minIdle;
    private int maxActive;


    /*配置获取连接等待超时的时间*/
    private long maxWait;
    /*配置间隔多久才进行一次检测，检测需要关闭的空闲连接，单位是毫秒*/
    private long timeBetweenEvictionRunsMillis;
    /*配置文件JSON信息*/
    private JSONObject properties;

    public DefaultDataSource(JSONObject  properties) {
        this.properties = properties;
        setUrl(SafeConvertUtil.toString(properties.get(AbsDataSource.URL)));
        setUserName(SafeConvertUtil.toString(properties.get(AbsDataSource.USER_NAME)));
        setPassword(SafeConvertUtil.toString(properties.get(AbsDataSource.PASS_WORD)));
        setDriver(SafeConvertUtil.toString(properties.get(AbsDataSource.DRIVER)));

        this.druidDataSource = new DruidDataSource();
        druidDataSource.setUrl(getUrl());
        druidDataSource.setUsername(getUserName());
        druidDataSource.setPassword(getPassword());
        druidDataSource.setDriverClassName(getDriver());

//        druidDataSource.setInitialSize(initialSize);
//        druidDataSource.setMinIdle(minIdle);
//        druidDataSource.setMaxActive(maxActive);

//        druidDataSource.setMaxWait(maxWait);
//        druidDataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
    }

    @Override
    public DataSource getDataSource() {
        return this.druidDataSource;
    }

    @Override
    public Connection getConnection() {
        Connection connection = null;
        try {
            connection = druidDataSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException("Get connection error!", e);
        }
        return connection;
    }

    @Override
    public boolean closeDataSource() {
        druidDataSource.close();
        return true;
    }

    public static void main(String[] args) {
        AbsDataSource absDataSource = new DefaultDataSource(new JSONObject());
    }
}
